define(function (require, exports, module) {
    require('authorize');
    var $ = require("jquery");
    var dialog = require("dialog");
    var util = require("util");
    var ui = require("ui");
    var angular = require("angular");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require("uploader");

    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/para-setting/"; //api前缀
    angular
        .module("PublicInviteBroker", ['ngRoute', 'ngUI', 'ngInterceptor'])
        .service("inviteBrokerSettingService", ['$http', function ($http) {
            return function () {
                return $http.get(api_prefix + 'get-invite-broker-data', {cache: false});
            }
        }])
        .controller("InviteBrokerController", ['$scope', 'inviteBrokerSettingService', '$http', function ($scope, inviteBrokerSettingService, $http) {
            var childCompanyRecord = function (record, isCheckAll, brokerIdentitySelectedAll) {
                var selected = record.selected;
                switch (record.Value) {
                    case '9003':
                        $scope.showAgentCompany = selected;
                        if (isCheckAll) {
                            $scope.data.agentCompany.selectedAll = selected;
                            checkAll($scope.data.agentCompany)
                        }
                        if (brokerIdentitySelectedAll) {
                            $scope.data.agentCompany.selectedAll = brokerIdentitySelectedAll;
                            checkAll($scope.data.agentCompany)
                        }
                        break;
                    case '9005':
                        $scope.showAgencyCompany = selected;
                        if (isCheckAll) {
                            $scope.data.agencyCompany.selectedAll = selected;
                            checkAll($scope.data.agencyCompany);
                        }
                        if (brokerIdentitySelectedAll) {
                            $scope.data.agencyCompany.selectedAll = brokerIdentitySelectedAll;
                            checkAll($scope.data.agencyCompany);
                        }
                        break;
                    case '9006':
                        $scope.showPartnerCompany = selected;
                        if (isCheckAll) {
                            $scope.data.partnerCompany.selectedAll = selected;
                            checkAll($scope.data.partnerCompany);
                        }
                        if (brokerIdentitySelectedAll) {
                            $scope.data.partnerCompany.selectedAll = brokerIdentitySelectedAll;
                            checkAll($scope.data.partnerCompany);
                        }
                        break;
                }
            };
            //经纪人类型全选取消
            $scope.updateBrokerIdentityCheckAll = function () {
                var data = $scope.data;

                if (data) {
                    var brokerIdentity = data.brokerIdentity;
                    var selectedAll = brokerIdentity.selectedAll;
                    for (var i = 0, item; item = brokerIdentity[i]; i++) {
                        item.selected = selectedAll;
                        childCompanyRecord(item, true);
                    }

                    if (data.agentCompany && data.agentCompany.enable) {
                        data.agentCompany.selectedAll = selectedAll;
                        $scope.updateAgentCompanyCheckAll();
                    }
                    if (data.agencyCompany && data.agencyCompany.enable) {
                        data.agencyCompany.selectedAll = selectedAll;
                        $scope.updateAgencyCompanyCheckAll();
                    }
                    if (data.partnerCompany && data.partnerCompany.enable) {
                        data.partnerCompany.selectedAll = selectedAll;
                        $scope.updatePartnerCompanyCheckAll();
                    }
                }
            };

            function isSelectedAll(list) {
                var checked;
                if (list && list.length > 0) {
                    checked = true;
                    for (var i = 0, item; item = list[i]; i++) {
                        if (!item.selected) {
                            checked = false;
                            break;
                        }
                    }
                } else {
                    checked = list.selectedAll;
                }

                return checked;
            }

            /**
             *
             * @param list
             * @returns {*}
             */
            function hasSelected(list) {
                var selected = false;
                if (list && list.length > 0) {
                    for (var i = 0, item; item = list[i]; i++) {
                        if (item.selected) {
                            selected = true;
                            break;
                        }
                    }
                } else {
                    selected = list.selectedAll;
                }

                return selected;
            }

            function setIdentitySelect(value, select) {
                var brokerIdentity = $scope.data.brokerIdentity;
                for (var i = 0, item; item = brokerIdentity[i]; i++) {
                    if (value === item.Value) {
                        item.selected = select;
                        break;
                    }
                }
            }

            function checkAll(agentCompany) {
                var selectedAll = agentCompany.selectedAll;
                for (var i = 0, item; item = agentCompany[i]; i++) {
                    item.selected = selectedAll;
                }
            }

            //经纪人类型同步全选/取消全选
            function brokerIdentityCheck() {
                var data = $scope.data;
                data.brokerIdentity.selectedAll =
                    isSelectedAll(data.brokerIdentity) &&
                    (!data.agentCompany.enable || isSelectedAll(data.agentCompany)) &&
                    (!data.agencyCompany.enable || isSelectedAll(data.agencyCompany) ) &&
                    (!data.partnerCompany.enable || isSelectedAll(data.partnerCompany));
            }

            $scope.updateBrokerIdentityCheck = function (record) {
                //含子公司的经济人类型
                childCompanyRecord(record, true);
                brokerIdentityCheck();
            };

            //代理公司全选/取消全选
            $scope.updateAgentCompanyCheckAll = function () {
                checkAll($scope.data.agentCompany);
                brokerIdentityCheck();

                var hasSelect = hasSelected($scope.data.agentCompany);
                setIdentitySelect('9003', hasSelect);
                $scope.showAgentCompany = hasSelect;
            };

            //代理公司同步全选/取消全选
            $scope.updateAgentCompanyCheck = function (item) {
                $scope.data.agentCompany.selectedAll = isSelectedAll($scope.data.agentCompany);
                brokerIdentityCheck();

                var hasSelect = hasSelected($scope.data.agentCompany);
                setIdentitySelect('9003', hasSelect);
                $scope.showAgentCompany = hasSelect;
            };

            //中介公司全选/取消全选
            $scope.updateAgencyCompanyCheckAll = function () {
                checkAll($scope.data.agencyCompany);
                brokerIdentityCheck();

                var hasSelect = hasSelected($scope.data.agencyCompany);
                setIdentitySelect('9005', hasSelect);
                $scope.showAgencyCompany = hasSelect;
            };

            //中介公司同步全选/取消全选
            $scope.updateAgencyCompanyCheck = function () {
                $scope.data.agencyCompany.selectedAll = isSelectedAll($scope.data.agencyCompany);
                brokerIdentityCheck();

                var hasSelect = hasSelected($scope.data.agencyCompany);
                setIdentitySelect('9005', hasSelect);
                $scope.showAgencyCompany = hasSelect;
            };

            //伙伴公司全选/取消全选
            $scope.updatePartnerCompanyCheckAll = function () {
                checkAll($scope.data.partnerCompany);
                brokerIdentityCheck();

                var hasSelect = hasSelected($scope.data.partnerCompany);
                setIdentitySelect('9006', hasSelect);
                $scope.showPartnerCompany = hasSelect;
            };

            //伙伴公司同步全选/取消全选
            $scope.updatePartnerCompanyCheck = function () {
                $scope.data.partnerCompany.selectedAll = isSelectedAll($scope.data.partnerCompany);
                brokerIdentityCheck();

                var hasSelect = hasSelected($scope.data.partnerCompany);
                setIdentitySelect('9006', hasSelect);
                $scope.showPartnerCompany = hasSelect;
            };

            //上传图片
            $scope.uploadImg = function () {
                $('#fileupload').fileupload({
                    dataType: 'json',
                    url: G_CONFIG["api_prefix"] + "common/file/upload-image-with-thumb",
                    add: function (e, data) {
                        data.submit();
                        $("#img_wrap").append('<div class="upload-process">上传中...</div>');
                    },
                    done: function (e, data) {
                        $("#img_wrap").find(".upload-process").remove();
                        var res = data.result;
                        if (res.retCode == "0") {
                            var img_url = res.data.path;
                            var thumbnail = res.data.thumbnail;
                            $scope.data.share_pic_url = img_url;
                            $scope.data.share_pic_name = res.data.name;
                            $scope.data.thumbnail = thumbnail;
                            $scope.$applyAsync();
                        } else {
                            $("#fileupload").nextAll(".js-err").html("上传失败:" + res.errMsg);
                            $("#share_invite_img").val("");
                        }
                    }
                });
            };

            function extractSelect(companies) {
                var str = '';
                if (companies.selectedAll) {
                    str = 'all';
                } else {
                    var arr = [];
                    for (var i = 0, item; item = companies[i]; i++) {
                        if (item.selected) {
                            arr.push(item.Value);
                        }
                    }
                    str = arr.join(',');
                }
                return str;
            }

            //保存邀请经纪人
            $scope.save = function () {
                var data = $scope.data;
                //待保存的数据
                var postData = {
                    token: util.getToken()
                };

                //是否开启邀请经纪人 0 关闭 1 开启
                if ($scope.showInvitebrokerMes) {
                    postData.enable = 1;

                    //经纪人身份
                    var brokerIdentity = data.brokerIdentity;
                    if (brokerIdentity.selectedAll) {
                        postData.brokerType = 'all';
                    } else {
                        var brokerIdentitySelects = [];
                        var item;
                        for (var i = 0; item = brokerIdentity[i]; i++) {
                            if (item.selected) {
                                brokerIdentitySelects.push(item.Value);
                            }
                        }

                        postData.brokerType = brokerIdentitySelects.join(',');
                    }
                    //邀请注册奖励
                    postData.bonus = data.inviteBrokerBonus;
                    //邀请经纪人活动规则设置
                    postData.rule = data.activity_rule;
                    //标题
                    postData.title = data.share_title;
                    //摘要
                    postData.summary = data.share_summary;
                    //图片路径
                    postData.urlPic = data.share_pic_url;
                    //缩略图
                    postData.thumbnail = data.thumbnail;
                    //图片名称
                    postData.picName = '上传.png';
                    //合作伙伴
                    postData.partnerCompany = extractSelect($scope.data.partnerCompany);
                    //代理公司
                    postData.agentCompany = extractSelect($scope.data.agentCompany);
                    //中介公司
                    postData.agencyCompany = extractSelect($scope.data.agencyCompany);
                } else {
                    postData.enable = 0;
                }

                $http.post(G_CONFIG.api_prefix + "qmyx/para-setting/save-invite-broker-data", postData)
                    .success(function (res) {
                        var retCode = res.retCode;
                        if (retCode == 0) {
                            ui.showSucTip();
                        }
                    })
            };

            function setSelectedStatus(companies, selects) {
                if (selects) {
                    var selectAll = selects.select === 'all';
                    for (var i = 0, item; item = companies[i]; i++) {
                        item.selected = selectAll || util.inArray(item.Value, selects.selected);
                    }

                    if (!selectAll) {
                        selectAll = isSelectedAll(selects);
                    }
                    companies.selectedAll = selectAll;
                }
            }

            inviteBrokerSettingService().success(function (res) {
                var data = res.data;

                var brokerIdentity = data.brokerIdentity;

                function inBroker(value) {
                    return util.inArray(value, brokerIdentity, function (id, item) {
                        return id === item.Value;
                    });
                }

                //代理公司
                setSelectedStatus(data.agentCompany, data.agentCompanySelect);
                data.agentCompany.enable = inBroker('9003');
                //中介公司
                setSelectedStatus(data.agencyCompany, data.agencyCompanySelect);
                data.agencyCompany.enable = inBroker('9005');
                //伙伴公司
                setSelectedStatus(data.partnerCompany, data.partnerCompanySelect);
                data.partnerCompany.enable = inBroker('9006');

                //选择启用该功能的经纪人类型
                var brokerIdentitySelect = data.brokerIdentitySelect;

                var brokerIdentitySelectAll;
                if (brokerIdentitySelect) {
                    brokerIdentitySelectAll = brokerIdentitySelect.select === 'all';
                } else {
                    brokerIdentitySelectAll = data.identity === 'all'
                }
                brokerIdentity.selectedAll = brokerIdentitySelectAll;

                data.activity_rule = data.activity_rule || '1、成功邀请好友注册成为全民经纪人，就有机会赢取奖励。\r\n2、邀请的好友成为经纪人之后，推荐客户成功购房，您也可以得到相应的佣金奖励。';
                //
                $scope.data = data;

                for (var i = 0, item; item = brokerIdentity[i]; i++) {
                    item.selected = brokerIdentitySelectAll || (!!brokerIdentitySelect && util.inArray(item.Value, brokerIdentitySelect));
                    childCompanyRecord(item, false, brokerIdentity.selectedAll);
                }

                $scope.showInvitebrokerMes = $scope.data.enable == 1;
                //邀请经纪人功能开关
                ui.initSwitch("#invitebroker_btn", function (data) {
                    $scope.showInvitebrokerMes = data.value == 1;
                    $scope.$applyAsync();
                });
                //邀请注册奖励
                if ($scope.data.enable == 1) {
                    ui.openSwitch("invitebroker_btn");
                } else {
                    ui.offSwitch("invitebroker_btn");
                }
            })
        }]);
});